# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import os
import sys
import subprocess
import threading

# Python 2/3 兼容导入
try:
    # Python 3
    import tkinter as tk
    from tkinter import messagebox, filedialog
except ImportError:
    # Python 2
    import Tkinter as tk
    import tkMessageBox as messagebox
    import tkFileDialog as filedialog

# 使用os.path代替pathlib
class Path(object):
    """简单的Path类模拟，用于在没有pathlib的环境中工作"""
    
    def __init__(self, path):
        self.path = str(path)
    
    @property
    def name(self):
        return os.path.basename(self.path)
    
    @property
    def stem(self):
        return os.path.splitext(os.path.basename(self.path))[0]
    
    @property
    def parent(self):
        return Path(os.path.dirname(self.path))
    
    def __str__(self):
        return self.path
    
    def __repr__(self):
        return "Path('{}')".format(self.path)
    
    def __truediv__(self, other):
        return Path(os.path.join(self.path, str(other)))
    
    def mkdir(self, exist_ok=False):
        if not os.path.exists(self.path):
            os.makedirs(self.path)
        elif not exist_ok:
            raise OSError("目录已存在: {}".format(self.path))
    
    def glob(self, pattern):
        import glob
        pattern_path = os.path.join(self.path, pattern)
        return [Path(p) for p in glob.glob(pattern_path)]

# 检查并安装所需的依赖包
def check_and_install_dependencies():
    """检查并安装所需的依赖包"""
    print("注意：您似乎没有安装pip。请手动安装以下依赖包：")
    print("- python-docx")
    print("- docx2pdf")
    print("- pdf2image")
    print("- pillow")
    print("您可以使用以下方法安装pip：")
    print("1. 下载 get-pip.py: curl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py")
    print("2. 运行: python get-pip.py")
    print("安装pip后，可以使用 pip install python-docx docx2pdf pdf2image pillow 安装依赖")
    
    answer = messagebox.askquestion("缺少依赖", 
                                   "程序需要几个依赖包才能工作。\n\n"
                                   "您想继续尝试运行程序吗？（可能会失败）")
    if answer != "yes":
        sys.exit(0)
    
    try:
        # 测试 pdf2image 是否已经安装
        import pdf2image
        
        # 测试 poppler 是否正确安装
        test_pdf = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test.pdf")
        with open(test_pdf, "w") as f:
            f.write("%PDF-1.0\n")
        try:
            pdf2image.convert_from_path(test_pdf, dpi=72, first_page=1, last_page=1)
            os.remove(test_pdf)
        except Exception as e:
            if "poppler" in str(e).lower():
                messagebox.showwarning("依赖缺失", "需要安装 Poppler 才能将 PDF 转换为图像。\n\n"
                                      "Windows: 下载并解压 poppler-xx.xx.x_x86.zip，然后将 bin 目录添加到系统环境变量 PATH 中。\n"
                                      "Mac: 使用 brew install poppler\n"
                                      "Linux: 使用 sudo apt-get install poppler-utils")
            os.remove(test_pdf)
    except ImportError:
        messagebox.showerror("缺少依赖", "pdf2image 模块未找到，程序无法继续。\n请安装所需依赖后再试。")
        sys.exit(1)
    except Exception as e:
        print("检查 pdf2image 出错: {}".format(e))

# 转换 Word 文档为图片集
def convert_word_to_images(word_path, output_dir=None):
    """
    将 Word 文档转换为图片集
    :param word_path: Word 文档路径
    :param output_dir: 输出目录，如果不指定，将在 Word 文件同级目录创建同名文件夹
    :return: 输出图片的目录
    """
    try:
        from docx2pdf import convert
        from pdf2image import convert_from_path
        import tempfile
    except ImportError:
        messagebox.showerror("缺少依赖", "缺少必要的依赖模块，请确保已安装 docx2pdf 和 pdf2image。")
        return None
    
    # 确定输出目录
    word_path = Path(word_path)
    if not output_dir:
        # 创建与 Word 文件同名的文件夹
        output_dir = word_path.parent / word_path.stem
    
    output_dir = Path(output_dir)
    output_dir.mkdir(exist_ok=True)
    
    # 创建临时 PDF 文件
    with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as temp_pdf:
        temp_pdf_path = temp_pdf.name
    
    try:
        # 转换 Word 到 PDF
        print("正在将 {} 转换为 PDF...".format(word_path.name))
        convert(word_path.path, temp_pdf_path)
        
        # 转换 PDF 到图片
        print("正在将 PDF 转换为图片...")
        images = convert_from_path(temp_pdf_path, dpi=300)
        
        # 保存图片
        for i, image in enumerate(images):
            image_path = output_dir / "page_{}.png".format(i+1)
            image.save(str(image_path), "PNG")
            print("已保存: {}".format(image_path))
        
        print("转换完成！图片已保存到: {}".format(output_dir))
        return output_dir
    
    finally:
        # 删除临时 PDF 文件
        if os.path.exists(temp_pdf_path):
            os.remove(temp_pdf_path)

# 处理目录中的所有 Word 文档
def process_all_word_docs(directory):
    """
    处理指定目录中的所有 Word 文档
    :param directory: 要处理的目录路径
    """
    directory = Path(directory)
    
    # 获取所有 Word 文档
    word_files = list(directory.glob("*.docx")) + list(directory.glob("*.doc"))
    
    if not word_files:
        messagebox.showinfo("提示", "在 {} 中未找到 Word 文档".format(directory))
        return
    
    total = len(word_files)
    for i, word_file in enumerate(word_files, 1):
        try:
            print("\n[{}/{}] 正在处理: {}".format(i, total, word_file.name))
            convert_word_to_images(word_file)
        except Exception as e:
            print("处理 {} 时出错: {}".format(word_file.name, e))
    
    messagebox.showinfo("完成", "已完成 {} 个 Word 文档的转换".format(total))

# GUI 界面
def create_gui():
    """创建图形用户界面"""
    root = tk.Tk()
    root.title("Word文档转图片工具")
    root.geometry("500x300")
    root.resizable(False, False)
    
    # 设置样式
    root.configure(bg="#f0f0f0")
    
    header = tk.Label(
        root,
        text="Word文档转图片工具",
        font=("微软雅黑", 16, "bold"),
        bg="#f0f0f0"
    )
    header.pack(pady=20)
    
    instruction = tk.Label(
        root,
        text="将Word文档转换为高质量图片集",
        font=("微软雅黑", 10),
        bg="#f0f0f0"
    )
    instruction.pack(pady=5)
    
    # 创建按钮框架
    button_frame = tk.Frame(root, bg="#f0f0f0")
    button_frame.pack(pady=30)
    
    # 选择文件按钮
    def select_file():
        file_path = filedialog.askopenfilename(
            title="选择Word文档",
            filetypes=[("Word文档", "*.docx;*.doc")]
        )
        if file_path:
            # 创建进度窗口
            progress_window = tk.Toplevel(root)
            progress_window.title("处理中")
            progress_window.geometry("300x100")
            progress_window.resizable(False, False)
            
            progress_label = tk.Label(
                progress_window,
                text="正在处理文档，请稍候...",
                font=("微软雅黑", 10)
            )
            progress_label.pack(pady=20)
            
            # 在新线程中转换文档
            def process_file():
                try:
                    output_dir = convert_word_to_images(file_path)
                    progress_window.destroy()
                    messagebox.showinfo("完成", "转换完成！\n图片已保存到: {}".format(output_dir))
                except Exception as e:
                    progress_window.destroy()
                    messagebox.showerror("错误", "转换过程中发生错误: {}".format(e))
            
            thread = threading.Thread(target=process_file)
            thread.daemon = True
            thread.start()
    
    select_file_btn = tk.Button(
        button_frame,
        text="选择单个Word文档",
        command=select_file,
        width=20,
        height=2,
        font=("微软雅黑", 10),
        bg="#4CAF50",
        fg="white",
        relief=tk.FLAT
    )
    select_file_btn.grid(row=0, column=0, padx=10)
    
    # 选择文件夹按钮
    def select_folder():
        folder_path = filedialog.askdirectory(title="选择包含Word文档的文件夹")
        if folder_path:
            # 创建进度窗口
            progress_window = tk.Toplevel(root)
            progress_window.title("处理中")
            progress_window.geometry("300x100")
            progress_window.resizable(False, False)
            
            progress_label = tk.Label(
                progress_window,
                text="正在处理文件夹中的所有文档，请稍候...",
                font=("微软雅黑", 10)
            )
            progress_label.pack(pady=20)
            
            # 在新线程中处理文件夹
            def process_folder():
                try:
                    process_all_word_docs(folder_path)
                    progress_window.destroy()
                except Exception as e:
                    progress_window.destroy()
                    messagebox.showerror("错误", "处理过程中发生错误: {}".format(e))
            
            thread = threading.Thread(target=process_folder)
            thread.daemon = True
            thread.start()
    
    select_folder_btn = tk.Button(
        button_frame,
        text="选择文件夹处理",
        command=select_folder,
        width=20,
        height=2,
        font=("微软雅黑", 10),
        bg="#2196F3",
        fg="white",
        relief=tk.FLAT
    )
    select_folder_btn.grid(row=0, column=1, padx=10)
    
    # 底部信息
    footer = tk.Label(
        root,
        text="© 2023 Word转图片工具",
        font=("微软雅黑", 8),
        bg="#f0f0f0",
        fg="#666666"
    )
    footer.pack(side=tk.BOTTOM, pady=10)
    
    root.mainloop()

# 主函数
def main():
    """主函数"""
    try:
        check_and_install_dependencies()
        create_gui()
    except Exception as e:
        messagebox.showerror("错误", "程序运行出错: {}".format(e))

if __name__ == "__main__":
    main() 